
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const jwtAuth = require('./utils/auth');//验证

//连接数据库-start
const mongoose = require('mongoose');
// 数据库地址
const dbURL = 'mongodb://localhost:27017/woniuExam'
mongoose.connect(dbURL, { useNewUrlParser: true, useUnifiedTopology: true })
mongoose.connection.on('connected', () => console.log(dbURL + ' 数据库连接成功'));
//连接数据库-end

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var errorsRouter = require('./routes/errors');
var collectionsRouter = require('./routes/collections');
var studentsRouter = require('./routes/students');
const imagesRouter=require('./routes/images');

var testsRouter = require('./routes/tests');
var typesRouter = require('./routes/examtypes');
var questionRouter = require('./routes/questions');
var completedTestRouter = require('./routes/completedTest');
// var knowledgesRouter = require('./routes/knowledgePoints');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 让 token 验证规则生效
// 一级接口之前
app.use(jwtAuth);
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/errors', errorsRouter);
app.use('/collections', collectionsRouter);
app.use('/students', studentsRouter);
app.use('/images',imagesRouter);


app.use('/tests', testsRouter);
app.use('/types', typesRouter);
app.use('/question', questionRouter);
app.use('/completedTest', completedTestRouter);
// app.use('/knowledgesRouter', knowledgesRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

app.listen(3001,()=>{
  console.log('服务器启动成功')
})

